package sc;

import java.awt.Component;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class Images extends Component
{
	private static final long serialVersionUID = 1L;
	private static Map<String, Image> images = new HashMap<String, Image>();
	private static Images instance = new Images();

	private Images()
	{
		
	}
	
	public static Image getImage(String path)
	{
		if (!images.containsKey(path))
		{
			try
			{
				URL url = instance.getClass().getResource(path);
				if (url == null)
				{
					Log.info("Requested image " + path + " not found");
					images.put(path, getImage("/images/unknown.png"));
					return images.get(path);
				}				
				Image image = Toolkit.getDefaultToolkit().createImage(url);
				MediaTracker mt = new MediaTracker(instance);
				mt.addImage(image, 0);
				mt.waitForAll();
				images.put(path, image);
			}
			catch (Exception e)
			{
				Log.info("Failed to get image " + path + ": " + e.getLocalizedMessage());
			}
		}
		return images.get(path);
	}
}
